// <reference path="node_modules\@types\three\build\three.module.d.ts" />
//npm i types/three
import * as THREE from "three"
const camera=new THREE.PerspectiveCamera(75,window.innerWidth/window.innerHeight,0.1,1000)
const box=new THREE.BoxGeometry(1,1,1)
const material=new THREE.MeshBasicMaterial({color:0xFFFFFF})
const playerCollider=new THREE.Mesh(box,material)
const scene=new THREE.Scene()
{

	const color = 0xFFFFFF;
	const intensity = 3;
	const light = new THREE.DirectionalLight( color, intensity );
	light.position.set( - 1, 2, 4 );
	scene.add( light );

}
scene.add(playerCollider)
camera.position.z=4
camera.position.y=2

const geometry = new THREE.PlaneGeometry( 10, 10 );
const plane_material = new THREE.MeshBasicMaterial( {color: 0x555555, side: THREE.DoubleSide} );
const plane = new THREE.Mesh( geometry, plane_material );
plane.rotateX(THREE.MathUtils.degToRad(90))
scene.add( plane );

const keyStates = {};


let playerOnFloor = false;
document.addEventListener( 'keydown', ( event ) => {

	keyStates[ event.code ] = true;

} );

document.addEventListener( 'keyup', ( event ) => {

	keyStates[ event.code ] = false;

} );

const playerVelocity = new THREE.Vector3();
const playerDirection = new THREE.Vector3();
function getForwardVector() {

	camera.getWorldDirection( playerDirection );
	playerDirection.y = 0;
	playerDirection.normalize();

	return playerDirection;

}
function getSideVector() {

	camera.getWorldDirection( playerDirection );
	playerDirection.y = 0;
	playerDirection.normalize();
	playerDirection.cross( camera.up );

	return playerDirection;

}
function controls( deltaTime ) {

	// gives a bit of air control
	const speedDelta = deltaTime * ( playerOnFloor ? 25 :8 );

	if ( keyStates[ 'KeyW' ] ) {

		playerVelocity.add( getForwardVector().multiplyScalar( speedDelta ) );

	}

	if ( keyStates[ 'KeyS' ] ) {

		playerVelocity.add( getForwardVector().multiplyScalar( - speedDelta ) );

	}

	if ( keyStates[ 'KeyA' ] ) {

		playerVelocity.add( getSideVector().multiplyScalar( - speedDelta ) );

	}

	if ( keyStates[ 'KeyD' ] ) {

		playerVelocity.add( getSideVector().multiplyScalar( speedDelta ) );

	}

	if ( playerOnFloor ) {

		if ( keyStates[ 'Space' ] ) {

			playerVelocity.y = 15;

		}

	}

}






const dom = document.querySelector('#container');
const renderer = new THREE.WebGLRenderer({antialias: true});
renderer.setSize(window.innerWidth,window.innerHeight)
dom.appendChild(renderer.domElement)

const clock = new THREE.Clock();
function render(){
	
	const deltaTime = Math.min( 0.05, clock.getDelta() ) / 1;

	// we look for collisions in substeps to mitigate the risk of
	// an object traversing another too quickly for detection.


	controls( deltaTime );
	// camera.lookAt(playerCollider.position)
	console.log(`playerVelocity:`,playerVelocity);
	playerCollider.position.add( playerVelocity );
	playerVelocity.sub(playerVelocity)
	renderer.render(scene,camera)
	requestAnimationFrame(render)
}
requestAnimationFrame(render)
